package com.ztesoft.zsmart.zcm.monitor.config;

import javax.sql.DataSource;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.ztesoft.zsmart.core.boot.autoconfigure.druid.DruidDataSourceBuilder;
import com.ztesoft.zsmart.core.boot.autoconfigure.druid.DruidDataSourceProperties;
import com.ztesoft.zsmart.core.jdbc.datasource.CoreDataSourceBean;
import com.ztesoft.zsmart.core.log.ZSmartLogger;

/**
 * TODO
 *
 * @Author FJJ
 * @Date 2018/7/4
 */
@Configuration
@AutoConfigureAfter(MybatisConfiguration.class)
@MapperScan(basePackages = "com.ztesoft.zsmart.zcm.monitor.mapper.cmdb", sqlSessionFactoryRef = "cmDBSqlSessionFactory")
// @ConditionalOnClass({DataSource.class, DruidDataSource.class})
public class CmDBDataSourceConfig {
    /** The logger. */
    private ZSmartLogger logger = ZSmartLogger.getLogger(CmDBDataSourceConfig.class);

    // 自定义数据源，参考DruidDataSourceAutoConfiguration中代码
    /** The Constant PREFIX. */
    // 需修改PREFIX的取值，去掉@Primary注解，重定义beanName，示例如下：
    private static final String PREFIX = "cmdb.datasource";

    /** The Constant PREFIX_DRUID. */
    private static final String PREFIX_DRUID = PREFIX + ".druid";

    /**
     * Properties pot.
     *
     * @return the druid data source properties
     */
    @Bean
    @ConfigurationProperties(PREFIX_DRUID)
    public DruidDataSourceProperties propertiesPot() {
        return new DruidDataSourceProperties();
    }

    /**
     * Druid data source.
     *
     * @return the core data source bean
     */
    // 注意，必须修改Bean的名称
    @Bean(name = "cmdbDataSource", initMethod = "init", destroyMethod = "close")
    @Qualifier("cmdbDataSource")
    // @ConditionalOnProperty(prefix = PREFIX_DRUID, value = "url")
    @ConfigurationProperties(PREFIX)
    public CoreDataSourceBean druidDataSource() {
        logger.info("-------------------- CmdbDataSource init ---------------------");
        DataSource druidDataSource = new DruidDataSourceBuilder().properties(propertiesPot()).build();
        return new CoreDataSourceBean(druidDataSource);
    }

}
